#include <opencv/cvaux.h>
#include <opencv/highgui.h>
#include <opencv/cxcore.h>
#include <stdio.h>


#define MAX_CAMERAS	100


//static CvCapture ** cameras = NULL;
static CvCapture * cameras[MAX_CAMERAS];
//static unsigned int numCams = 0;


int init_cameras(unsigned int cam) {
//    cameras = (CvCapture **) malloc(num * sizeof(CvCapture*));

//    if (!cameras)
//        return -1;

//    numCams = num;
//    memset(cameras, 0, num*sizeof(CvCapture*));
    memset(cameras, 0, MAX_CAMERAS*sizeof(CvCapture*));

int    i = cam;

//    for (unsigned int i = 0; i < num; i++) {
        cameras[i] = cvCreateCameraCapture(i); // Use the default camera
        //camera[i] = cvCreateCameraCapture(-1); // Use the default camera
        //camera = cvCaptureFromCAM(-1);

        //if (!cameras[i])
        //    return -1;

//        cvSetCaptureProperty(cameras[i], CV_CAP_PROP_EXPOSURE, 0);
//        cvSetCaptureProperty(cameras[i], CV_CAP_PROP_FPS, 30);

//        cvSetCaptureProperty(cameras[i], CV_CAP_PROP_FRAME_WIDTH, 640);
//        cvSetCaptureProperty(cameras[i], CV_CAP_PROP_FRAME_HEIGHT, 480);
        cvSetCaptureProperty(cameras[i], CV_CAP_PROP_FRAME_WIDTH, 320);
        cvSetCaptureProperty(cameras[i], CV_CAP_PROP_FRAME_HEIGHT, 240);
//    }

    return 0;
}


void deinit_camera(int cam) {
//    if (cameras) {
int i = cam;
//        for (unsigned int i = 0; i < numCams; i++)
            cvReleaseCapture(&cameras[i]);
//    }
}


int get_frame(int cam, int * width, int * height, char ** buffer) {
    int ret = 0;
    IplImage * currFrame = cvQueryFrame(cameras[cam]);

//    int err = cvGrabFrame(camera[cam]);
//    IplImage * currFrame = cvRetrieveFrame(cameras[cam]);

    if (currFrame != NULL) {
        *width = currFrame->width;
        *height = currFrame->height;
        *buffer = currFrame->imageData;
        ret = currFrame->imageSize;
    } else {
        ret = -1;
    }

    return ret;
}
